package com.it.schoolbookshop_back.mapper;

import com.it.schoolbookshop_back.entities.po.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface MessageMapper {
    @Insert("INSERT INTO messages(sender_id, receiver_id, book_id, content, is_read) " +
            "VALUES(#{senderId}, #{receiverId}, #{bookId}, #{content}, #{isRead})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertMessage(Message message);

    @Select("SELECT * FROM messages WHERE (sender_id = #{userId1} AND receiver_id = #{userId2}) " +
            "OR (sender_id = #{userId2} AND receiver_id = #{userId1}) ORDER BY created_at ASC")
    List<Message> getMessagesBetweenUsers(@Param("userId1") int userId1, @Param("userId2") int userId2);
    
    /**
     * 获取与用户聊天的所有伙伴ID
     */
    @Select("SELECT DISTINCT CASE " +
            "WHEN sender_id = #{userId} THEN receiver_id " +
            "ELSE sender_id END AS partner_id " +
            "FROM messages " +
            "WHERE sender_id = #{userId} OR receiver_id = #{userId}")
    List<Integer> getUserChatPartners(@Param("userId") Integer userId);
    
    /**
     * 获取两个用户之间的最后一条消息
     */
    @Select("SELECT * FROM messages " +
            "WHERE (sender_id = #{userId1} AND receiver_id = #{userId2}) " +
            "OR (sender_id = #{userId2} AND receiver_id = #{userId1}) " +
            "ORDER BY created_at DESC LIMIT 1")
    Message getLastMessageBetweenUsers(@Param("userId1") Integer userId1, @Param("userId2") Integer userId2);
    
    /**
     * 统计未读消息数量
     */
    @Select("SELECT COUNT(*) FROM messages " +
            "WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} AND is_read = false")
    int countUnreadMessages(@Param("senderId") Integer senderId, @Param("receiverId") Integer receiverId);
    
    /**
     * 根据ID获取消息
     */
    @Select("SELECT * FROM messages WHERE id = #{messageId}")
    Message getMessageById(@Param("messageId") Integer messageId);
    
    /**
     * 标记消息为已读
     */
    @Update("UPDATE messages SET is_read = true WHERE id = #{messageId}")
    int markMessageAsRead(@Param("messageId") Integer messageId);
    
    /**
     * 标记特定发送者发送给特定接收者的所有未读消息为已读
     */
    @Update("UPDATE messages SET is_read = true WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} AND is_read = false")
    int markAllMessagesAsRead(@Param("senderId") Integer senderId, @Param("receiverId") Integer receiverId);
}